package net.zretc.controller;

import net.zretc.entity.Admin;
import net.zretc.entity.User;
import net.zretc.service.AdminService;
import net.zretc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admins")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Admin admin) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = adminService.register(admin);
            if (success) {
                result.put("success", true);
                result.put("message", "管理员注册成功");
            } else {
                result.put("success", false);
                result.put("message", "管理员注册失败，用户名可能已存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册出错，请稍后再试");
            System.err.println("注册出错: " + e.getMessage());
        }
        return result;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Admin admin) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 使用UserService来验证管理员登录，因为管理员也存储在users表中
            User loggedInUser = userService.login(admin.getUsername(), admin.getPassword());
            if (loggedInUser != null && loggedInUser.isAdmin()) {
                result.put("success", true);
                result.put("message", "管理员登录成功");
                result.put("user", loggedInUser);
                result.put("userType", "admin");
            } else {
                result.put("success", false);
                result.put("message", "用户名或密码错误，或者不是管理员账号");
            }
        } catch (Exception e) {
            System.err.println("登录出错: " + e.getMessage());
            result.put("success", false);
            result.put("message", "登录出错，请稍后再试");
        }
        return result;
    }
}
